// pages/product/productDetails.js
var Zan = require('../../dist/index');
var WxParse = require('../../wxParse/wxParse.js');
var network = null;
var utils = null;
var api = null;
const app = getApp();
var eventStatus = 0; // 0=没选规格;1=加入购物车;2=立即购买

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    listSpec: [],
    showDialog: false,
    count: 1,
    radioCheckVal01: 0,
    radioCheckVal02: 0,
    radioCheckVal03: 0,
    price: 0,
    selectedSpec: null,
    mobile: null,
    productId: '',
    intelvalue01: 0,
    intelvalue02: 0,
    intelvalue03: 0,
    item01: '',
    item02: '',
    item03: '',
    listspecid: '',
    RealListspec: {},
    formId: '',
    showFillBtn: false,
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 400
      },
      videoHeight: utils.windowSize().winWidth / 750 * 402
    })

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        bind(options);
      }
    }
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    wx.getUserInfo({
      success: res => {
        this.setData({
          nickName: res.userInfo.nickName,
        })
      }
    })

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })

    // this.setData({
    //   productId: options.productId
    // })
    network._post_json(this, api.getProductDetails, { productId: options.productId }, success);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    eventStatus = 0;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: this.data.product.title,
      path: '/pages/product/ProductDetails?shared=' + app.globalData.userAndTenantInfo.id + '&productId=' + this.data.product.id,
      // imageUrl: this.data.saleInfo.qrCode,
      success: function (res) {
        // 转发成功
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets,
            success: function (res) {
              network._post_json(that, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
            },
            fail: function (res) {
              // 转发失败
              network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
            }
          })
        } else {
          network._post_json(that, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    })
    
  },
  

  /**
   * 进入下一步提交订单
   */
  next: function (e) {
    // var index = e.currentTarget.dataset.index;
    

    var checkFlag = isSelectedOk(this);
    if (checkFlag == -3) {
      this.setData({
        showDialog: false,
      });
      //还原设定
      eventStatus = 0;
    } else if (checkFlag == -1) {
      this.showZanTopTips(this.prompt, "库存不足");
    } else if (checkFlag == -2) {
      this.showZanTopTips(this.prompt, "购买数量大于限购数量");
    } else {
      this.setData({
        showDialog: false
      });
     
      if (eventStatus == 1) {
        addShoppingCart(this);
      } else if (eventStatus == 2) {
        startPay(this);
      }
      //还原设定
      eventStatus = 0;
    }
    
    
  },


  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      this.setData({
        count: this.data.count
      });

      calcPoint(this);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    this.data.count++;
    this.setData({
      count: this.data.count
    });

    calcPoint(this);
  },

  /**
   * 如果用户已授权，并且用户昵称不为空，则直接弹框
   */
  chooseSpan: function (e) {
    var event = e.currentTarget.dataset.event;
    if (this.data.product.isVirtual == 0 && this.data.product.isActive == 1) {
      eventStatus = event;
      var checkFlag = isSelectedOk(this);
      //当前已经选好，直接购买
      if (checkFlag == 1) {
        if (eventStatus == 1) {
          addShoppingCart(this);
        } else if (eventStatus == 2) {
          startPay(this);
        }
      } else {
        //需要继续选择规格和数量        
        this.setData({
          showDialog: true,
        });
      }
      
    } else {
      this.showZanTopTips(this.prompt, '商品已下架');
    }
  },

  formSubmit: function (e) {
    this.setData({
      formId: e.detail.formId
    })
  },

  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },//进入购物车
  go_shopcar: function (e) {
    wx.navigateTo({
      url: '/pages/shoppingCar/ShoppingCar',
    })
  },

  //选择一个规格后
  specSelect: function (e) { 
    var currData = e.currentTarget.dataset;
    var fatidx = currData.fatidx;
    var subidx = currData.subidx;
    var currBind = this.data.specArr[fatidx].specDetails[subidx];
    
    if (currBind.class) {
      currBind.class = "";
    } else {
      currBind.class = "active";
    }


    //处理当前选择的规格类型的其他规格
    for (var n = 0; n < this.data.specArr[fatidx].specDetails.length; n++) {
      if (this.data.specArr[fatidx].specDetails[n].class == "active" && subidx != n) {
        this.data.specArr[fatidx].specDetails[n].class = "";
      }
    }

    this.setData(this.data);

    calcPoint(this);
  },

  startPlay: function (e) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf("iOS") >= 0) {
          let id = e.target.dataset.id;
          wx.createVideoContext(id).play();
          wx.createVideoContext(id).pause();
        }
      }
    })
  },

  not: function (e) {
    let id = e.target.dataset.id;
    wx.createVideoContext(id).play();
    wx.createVideoContext(id).pause();
  },

}))
//Page结束


// 生成小程序显示的规格数据
var buildSpecArr = function (that, res) {
  var specArr = [];
  for (var i = 1; i < 4; i++) {
    if (res.data.data.product["specType" + i]) {
      specArr[i - 1] = {
        specType: res.data.data.product["specType" + i],
        specDetails: []
      };
    } else {
      break;
    }
  }
  
  for (var m = 0; m < res.data.data.product.listSpecGroups.length; m++) {
    for (var n = 0; n < specArr.length; n++) {
      var isSame = false;
      var specTmp = res.data.data.product.listSpecGroups[m]["specDetails" + (n + 1)];
      if (specArr[n].specDetails.length) {
        for (var s = 0; s < specArr[n].specDetails.length; s++) {
          if (specArr[n].specDetails[s].name == specTmp) {
            isSame = true;
            break;
          }
        }
      }
      if (!isSame) {
        specArr[n].specDetails.push({
          name: specTmp,
          class: ""
        });
      }
    }
  }

  that.setData({
    specArr: specArr
  })
  
}

//计算当前价格
var calcPoint = function (that) {  
  //多规格
  if (that.data.product.specClass == 2) {
    //检查是否选择了全部类型的规格
    var selectedSpec = [];
    for (var m = 0; m < that.data.specArr.length; m++) {
      for (var n = 0; n < that.data.specArr[m].specDetails.length; n++) {
        if (that.data.specArr[m].specDetails[n].class == "active") {
          selectedSpec.push(that.data.specArr[m].specDetails[n].name);
          break;
        }
      }
    }
    //规格都选了
    if (selectedSpec.length == that.data.specArr.length) {
      for (var m = 0; m < that.data.product.listSpecGroups.length; m++) {
        var isCurr = true;
        for (var n = 0; n < selectedSpec.length; n++) {
          if (that.data.product.listSpecGroups[m]["specDetails" + (n + 1)] != selectedSpec[n]) {
            isCurr = false;
            break;
          }
        }
        if (isCurr) {
          var selectedSpecNames = "";
          for (var n = 0; n < selectedSpec.length; n++) {
            if (n != 0) {
              selectedSpecNames += "+";
            }
            selectedSpecNames += selectedSpec;
          }
          that.setData({
            selectedSpecNames: selectedSpec,
            selectedSpecRowIdx: m,
            selectedSpecRow: that.data.product.listSpecGroups[m],
            currProPrice: that.data.product.listSpecGroups[m].specValue1 * that.data.count / 100,
            currStoreCount: that.data.product.listSpecGroups[m].storeCount,
            currLimitCount: that.data.product.listSpecGroups[m].limitCount
          })
        }
      }
    } else {
      //没选全规格，计算价格的范围
      var  minProPrice, maxProPrice;
      for (var m = 0; m < that.data.product.listSpecGroups.length; m++) {
        if (m == 0) {          
          minProPrice = that.data.product.listSpecGroups[m].specValue1;
          maxProPrice = that.data.product.listSpecGroups[m].specValue1;
        } else {          
          if (minProPrice > that.data.product.listSpecGroups[m].specValue1) {
            minProPrice = that.data.product.listSpecGroups[m].specValue1;
          }          
          if (maxProPrice < that.data.product.listSpecGroups[m].specValue1) {
            maxProPrice = that.data.product.listSpecGroups[m].specValue1;
          }
        }
      }
      var currProPrice = 0;
      if (minProPrice == maxProPrice){
        currProPrice = minProPrice /100;
      }else{
        currProPrice = (minProPrice / 100) + "-" + (maxProPrice / 100);
      }
      that.setData({
        selectedSpecNames: "",
        currProPrice: currProPrice,
        selectedSpecRow: null,
        currStoreCount: "",
        currLimitCount: ""
      })
    }
  } else {
    //统一规格
    that.setData({
      selectedSpecNames: "",
      currProPrice: that.data.product.price * that.data.count / 100,
      currStoreCount: that.data.product.storeCount,
      currLimitCount: that.data.product.limitCount
    })

  }

}

//校验当前选择的规格及数量是否可以购买
var isSelectedOk = function (that) {
  //多规格
  if (that.data.product.specClass == 2) {
    if (that.data.selectedSpecRow) {
      if (that.data.selectedSpecRow.storeCount <= 0 || that.data.selectedSpecRow.storeCount < that.data.count) {
        //库存不足
        return -1;
      } else if (that.data.count > that.data.selectedSpecRow.limitCount) {
        //数量超出限购数量
        return -2;
      } else {
        return 1;
      }
    } else {
      //规格没选
      return -3;
    }
  }else{
    if (that.data.product.storeCount <= 0 || that.data.product.storeCount < that.data.count) {
      //库存不足
      return -1;
    } else if (that.data.count > that.data.product.limitCount) {
      //数量超出限购数量
      return -2;
    } else {
      return 1;
    }
  }
  
}

// 获取商品列表结果
var success = function (that, res) {
  var arr = new Array();
  var listspecs = {};
  var initiallistspecs = {}

  if (res.data.data.product.specClass == 2) {
    buildSpecArr(that, res);
  } else {

  }
  
  if (res.data.data) {
    that.setData({
      product: res.data.data.product,
      listSpec: res.data.data.product.listSpecGroups,
      listspecs: listspecs,
      initiallistspecs: initiallistspecs
    })
    WxParse.wxParse('details', 'html', res.data.data.product.productDetail.detail, that, 0);
    
    calcPoint(that);

  }
}

var addSuccess = function (that, res) {
  // that.setData({
  //   count: 1,
  //   radioCheckVal: 0,
  //   selectedSpec: that.data.listSpec[0]
  // })
  // allPrice(that, that.data.product);
  that.showZanToast('添加成功');
}

var addShoppingCart = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    //多规格
    if (that.data.product.specClass == 2) {
      network._post_json(that, api.addShoppingCart, { product: { productId: that.data.product.id, specId: that.data.selectedSpecRow.id, count: that.data.count } }, addSuccess);
    }else{
      // 没有规格的商品
      network._post_json(that, api.addShoppingCart, { product: { productId: that.data.product.id, count: that.data.count } }, addSuccess);
    }
    
  } else {
    that.showZanTopTips(that.prompt,'商品已下架');
  }
}

var startPay = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    var product = {};
    var products = [];
    product.id = that.data.product.id;
    product.title = that.data.product.title;
    product.smallImgUrl = that.data.product.smallImgUrl;
    product.count = that.data.count;

    //多规格
    if (that.data.product.specClass == 2) {
      product.price = that.data.currProPrice / that.data.count * 100;
      product.specId = that.data.selectedSpecRow.id;
      product.specName = that.data.selectedSpecNames.join();
      product.selectedSpec = that.data.selectedSpecRow;

      console.log('huanghe');
      console.log(that.data.selectedSpecNames)
      console.log(product.specName)
      
    } else {
      // 没有规格的商品
      product.price = that.data.product.price;
    }

    products.push(product);
    try {
      wx.setStorageSync('products', products)
    } catch (e) {
    }
    
    wx.navigateTo({
      url: '/pages/pay/Pay'
    })
  } else {
    that.showZanTopTips(that.prompt, '商品已下架');
  }
}

var bindSuccess = function (that, res) {
  if (that.data.formId && app.globalData.userAndTenantInfo.mobile != res.data.data.mobile) {
    network._post_json(that, api.sendCoupn, { formId: that.data.formId, type: 2 }, sendCoupnSuccess);
  }

  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        productId: options.productId
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}

var sendCoupnSuccess = function (that, res) { }